package com.itheima.controller;


/*
 *   抽取一个基本serlet  使用uri提取方法名
 * */

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.domain.SysLog;
import com.itheima.domain.UserInfo;
import com.itheima.service.login.LoginService;
import com.itheima.service.login.impl.LoginServiceImpl;
import com.itheima.service.oders.OrdersService;
import com.itheima.service.oders.impl.OrdersServiceImpl;
import com.itheima.service.permission.PermissionService;
import com.itheima.service.permission.impl.PermissionServiceImpl;
import com.itheima.service.product.ProductService;
import com.itheima.service.product.impl.ProductServiceImpl;
import com.itheima.service.role.RoleService;
import com.itheima.service.role.impl.RoleServiceImpl;
import com.itheima.service.syslog.SysLogService;
import com.itheima.service.syslog.impl.SysLogServiceImpl;
import com.itheima.service.user.UserService;
import com.itheima.service.user.impl.UserServiceImpl;
import com.itheima.utils.GetSysLogUtil;
import com.itheima.utils.PermissionUtil;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {

    public long time;

    //业务层对象 在此定义
    public LoginService loginService = null;
    public SysLogService sysLogService = null;
    public OrdersService ordersService = null;
    public PermissionService permissionService = null;
    public RoleService roleService = null;
    public ProductService productService = null;
    public UserService userService = null;
    //json工具对象
    public ObjectMapper mapper;

    @Override
    public void init() throws ServletException {
        //各个业务层对象初始化 在此赋值
        loginService = new LoginServiceImpl();
        sysLogService = new SysLogServiceImpl();
        ordersService = new OrdersServiceImpl();
        permissionService = new PermissionServiceImpl();
        roleService = new RoleServiceImpl();
        productService = new ProductServiceImpl();
        userService = new UserServiceImpl();
        //创建Json转换对象
        mapper = new ObjectMapper();
    }

    //使用反射抽取方法名
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取统一资源标识符
        String uri = req.getRequestURI();
//        System.out.println("uri = " + uri);

        //抽取方法名
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);

        //获得url 格式:http://localhost:8090/BackgroundManager/orders/findAll
        StringBuffer urlStringBuffer = req.getRequestURL();
        String url = urlStringBuffer.toString();
        System.out.println("url = " + url);
        String nullString = "";
        //权限路径 格式:/orders/findAll
        String path = url.replace("http://localhost:8090/BackgroundManager", nullString);
        System.out.println("path = " + path);


        UserInfo userInfo = (UserInfo) req.getSession().getAttribute("user");
        System.out.println("userInfo = " + userInfo);

//        Boolean hasPermssion = PermissionUtil.hasPermssion(path, userInfo);
//        System.out.println("hasPermssion = " + hasPermssion);

        if (userInfo == null) {
            try {
                //获取方法对象
                Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
                //暴力反射
                method.setAccessible(true);
                //方法执行前获取当前系统时间
                long timeBefore = System.currentTimeMillis();
                //调用方法
                method.invoke(this, req, resp);
                //方法执行后再获取一次时间
                long timeAfter = System.currentTimeMillis();
                //获取方法执行时间
                time = timeAfter - timeBefore;

                SysLog sysLog = GetSysLogUtil.getSysLog(req, resp);
                if (sysLog != null) sysLog.setExecutionTime(time);
                sysLogService.save(sysLog);

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            if(PermissionUtil.hasPermssion(path, userInfo)){
                try {
                    //获取方法对象
                    Method method = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
                    //暴力反射
                    method.setAccessible(true);
                    //方法执行前获取当前系统时间
                    long timeBefore = System.currentTimeMillis();
                    //调用方法
                    method.invoke(this, req, resp);
                    //方法执行后再获取一次时间
                    long timeAfter = System.currentTimeMillis();
                    //获取方法执行时间
                    time = timeAfter - timeBefore;

                    SysLog sysLog = GetSysLogUtil.getSysLog(req, resp);
                    if (sysLog != null) sysLog.setExecutionTime(time);
                    sysLogService.save(sysLog);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else {
                req.getRequestDispatcher("/pages/common/noPermission.jsp").forward(req,resp);
            }
        }
    }
}
